package com.ruoyi.pingan.fymodule.thirdpa.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.pingan.config.PayConfig;
import com.ruoyi.pingan.config.TaskExecutePoolConfig;
import com.ruoyi.pingan.fymodule.account.entity.SxoSafetyUser;
import com.ruoyi.pingan.fymodule.account.enums.CodeEnum;
import com.ruoyi.pingan.fymodule.account.service.ISxoSafetyLogService;
import com.ruoyi.pingan.fymodule.account.service.ISxoSafetyUserService;
import com.ruoyi.pingan.fymodule.account.util.HttpResult;
import com.ruoyi.pingan.fymodule.account.util.PaPayUtil;
import com.ruoyi.pingan.fymodule.account.util.TradetraceUtil;
import com.ruoyi.pingan.fymodule.exception.BusinessException;
import com.ruoyi.pingan.fymodule.order.entity.*;
import com.ruoyi.pingan.fymodule.order.service.*;
import com.ruoyi.pingan.fymodule.plugins.entity.SxoPluginsShop;
import com.ruoyi.pingan.fymodule.plugins.service.ISxoPluginsShopService;
import com.ruoyi.pingan.fymodule.sxosafetyaccountrecord.entity.SxoSafetyAccountRecord;
import com.ruoyi.pingan.fymodule.sxosafetyaccountrecord.service.SxoSafetyAccountRecordService;
import com.ruoyi.pingan.fymodule.thirdpa.api.IBaseClient;
import com.ruoyi.pingan.fymodule.thirdpa.api.impl.*;
import com.ruoyi.pingan.fymodule.thirdpa.model.dto.*;
import com.ruoyi.pingan.fymodule.thirdpa.model.vo.*;
import com.ruoyi.pingan.fymodule.thirdpa.service.PaOrderService;
import com.ruoyi.pingan.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class PaOrderServiceImpl extends BasePaServiceImpl implements PaOrderService {


    @Autowired
    private ISxoSafetyLogService sxoSafetyLogService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private TaskExecutePoolConfig taskExecutePoolConfig;
    @Autowired
    private ISxoPaymentService sxoPaymentService;
    @Autowired
    private ISxoOrderService sxoOrderService;
    @Autowired
    private ISxoOrderDetailService sxoOrderDetailService;
    @Autowired
    private ISxoSafetyOrderService sxoSafetyOrderService;
    @Autowired
    private ISxoSafetyOrderDetailService sxoSafetyOrderDetailService;
    @Autowired
    private ISxoSafetyOrderRevokeService sxoSafetyOrderRevokeService;
    @Autowired
    private ISxoSafetyOrderRevokeDetailService sxoSafetyOrderRevokeDetailService;
    @Autowired
    private ISxoSafetySepAccService sxoSafetySepAccService;
    @Autowired
    private ISxoSafetySepAccDetailService sxoSafetySepAccDetailService;
    @Autowired
    private ISxoSafetySepAccRevokeDetailService sxoSafetySepAccRevokeDetailService;
    @Autowired
    private ISxoSafetyUserService sxoSafetyUserService;
    @Autowired
    private ISxoRefundLogService sxoRefundLogService;
    @Autowired
    private ISxoSafetyOrderSubsidyService sxoSafetyOrderSubsidyService;
    @Autowired
    private ISxoSafetyRegCreditService sxoSafetyRegCreditService;
    @Autowired
    private PaOrderService paOrderService;
    @Autowired
    private ISxoOrderAftersaleService iSxoOrderAftersaleService;

    @Autowired
    private ISxoPluginsShopService iSxoPluginsShopService;
    @Autowired
    private ISxoSafetySepAccRevokeService sxoSafetySepAccRevokeService;
    @Autowired
    private SxoSafetyAccountRecordService sxoSafetyAccountRecordService;



    @Override
    public ThirdFreezeRechargeVo thirdFreezeRecharge(ThirdFreezeRechargeDto dto) {
        if (StrUtil.isEmpty(dto.getId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "id必须填写");
        }

        LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrder::getOrderId, dto.getId());
        queryWrapper.eq(SxoSafetyOrder::getOrdersStatus, "1");
        queryWrapper.eq(SxoSafetyOrder::getStatus, "0");
        List<SxoSafetyOrder> safetyOrders = sxoSafetyOrderService.list(queryWrapper);
        if (safetyOrders.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "当前订单已存在冻结充值；无法重复推送");
        }
        SxoSafetyOrder sxoOrder = safetyOrders.get(0);

        LambdaQueryWrapper<SxoSafetyOrderDetail> detailsQueryWrapper = new LambdaQueryWrapper<>();
        detailsQueryWrapper.eq(SxoSafetyOrderDetail::getSafetyOrderId, sxoOrder.getId());
        List<SxoSafetyOrderDetail> orderDetails = sxoSafetyOrderDetailService.list(detailsQueryWrapper);

        String cnsmrSeqNo = PaPayUtil.getCnsmrSeqNo();
        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6267");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        json.put(PaPayUtil.CNSMR_SEQ_NO, cnsmrSeqNo);
        //订单信息
        String merNo = payConfig.getMerNo();
        String payChannelType = "0040";
        json.put("PayChannelType", payChannelType);
        json.put("PayChannelAssignMerNo", merNo);
        json.put("PayOrderDate", sxoOrder.getPayOrderDate());
        json.put("TotalOrderNo", sxoOrder.getTotalOrderNo());//第三方支付渠道产生的支付订单号
        json.put("TranTotalAmt", sxoOrder.getOrderTotalAmt());

        SxoSafetyOrder mod = new SxoSafetyOrder();
        //分账信息
        List<Map<String, Object>> tranItems = new ArrayList<>();
        //多条要考虑运费的情况，运费也要加入到子数组
        String ordersCount = String.valueOf(orderDetails.size());
        int a = 0;
        LambdaQueryWrapper<SxoOrder> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(SxoOrder::getId, dto.getId());
        List<SxoOrder> orderList = sxoOrderService.list(orderWrapper);
        SxoOrder sxoOrder1 = orderList.get(0);
        BigDecimal yfdecimal = new BigDecimal(sxoOrder1.getFreightfee());
        BigDecimal rounded = yfdecimal.setScale(2, RoundingMode.HALF_UP); // 设置为两位小数并四舍五入
        double doubleValue = rounded.doubleValue();
        if(doubleValue>0){
            Map<String, Object> yfitem = new HashMap<>();
            yfitem.put("SubOrderFillSubAcctNo", orderDetails.get(0).getSubOrderFillSubAcctNo());
            yfitem.put("SubOrderFillAmt", sxoOrder1.getFreightfee());
            yfitem.put("SubOrderFillCommission", orderDetails.get(0).getSubOrderFillCommission());
            String yfId = TradetraceUtil.buildTradetracePay();
            yfitem.put("SubFillOrderNo", yfId);
            yfitem.put("SubOrderFillDesc", orderDetails.get(0).getSubOrderFillDesc());//描述订单的用途
            yfitem.put("SubOrderFillRemark", orderDetails.get(0).getSubOrderFillRemark());
            yfitem.put("SubOrderFillReservedMsg", "");
            tranItems.add(yfitem);
            sxoOrder1.setFrozenFreightfeeId(yfId);
            mod.setFrozenFreightfeeId(yfId);
            sxoOrderService.updateById(sxoOrder1);
            a = 1;

        }
        if(orderDetails.size()>1){
            //多条要考虑运费的情况，运费也要加入到子数组

            for (SxoSafetyOrderDetail sxoOrderDetail : orderDetails) {
                Map<String, Object> item = new HashMap<>();
                item.put("SubOrderFillSubAcctNo", sxoOrderDetail.getSubOrderFillSubAcctNo());
                LambdaQueryWrapper<SxoOrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
                orderDetailWrapper.eq(SxoOrderDetail::getOrderId, dto.getId());
                orderDetailWrapper.eq(SxoOrderDetail::getGoodsId, sxoOrderDetail.getGoodsId());
                List<SxoOrderDetail> orderDetailList = sxoOrderDetailService.list(orderDetailWrapper);
                item.put("SubOrderFillAmt", orderDetailList.get(0).getTotalPrice());
                item.put("SubOrderFillCommission", sxoOrderDetail.getSubOrderFillCommission());
                item.put("SubFillOrderNo", sxoOrderDetail.getSubFillOrderNo());
                item.put("SubOrderFillDesc", sxoOrderDetail.getSubOrderFillDesc());//描述订单的用途
                item.put("SubOrderFillRemark", sxoOrderDetail.getSubOrderFillRemark());
                item.put("SubOrderFillReservedMsg", "");
                tranItems.add(item);
            }
            ordersCount = String.valueOf(orderDetails.size()+a);
            json.put("OrdersCount", ordersCount);

        }
        if(orderDetails.size()==1 ){
            for (SxoSafetyOrderDetail sxoOrderDetail : orderDetails) {
                Map<String, Object> item = new HashMap<>();
                item.put("SubOrderFillSubAcctNo", sxoOrderDetail.getSubOrderFillSubAcctNo());
                item.put("SubOrderFillAmt", sxoOrderDetail.getSubOrderFillAmt());
                item.put("SubOrderFillCommission", sxoOrderDetail.getSubOrderFillCommission());
                item.put("SubFillOrderNo", sxoOrderDetail.getSubFillOrderNo());
                item.put("SubOrderFillDesc", sxoOrderDetail.getSubOrderFillDesc());//描述订单的用途
                item.put("SubOrderFillRemark", sxoOrderDetail.getSubOrderFillRemark());
                item.put("SubOrderFillReservedMsg", "");
                tranItems.add(item);
            }

            json.put("OrdersCount", String.valueOf(a+1));
        }

        json.put("TranItemArray", tranItems);


        mod.setId(sxoOrder.getId());
        mod.setUpdTime(DateUtil.now());

        ThirdFreezeRechargeVo vo = new ThirdFreezeRechargeVo();
        try {
            IBaseClient baseClient = new ThirdFreezeRechargeApi(sxoSafetyLogService, taskExecutePoolConfig);
            log.info("6267调平安入参："+json);
            log.info("6267调平安入参时间:{}", DateUtil.now());
            HttpResult httpResult = baseClient.execute(json);
            JSONObject extenddata = handleError(httpResult);
            log.info("6267调平安回参："+extenddata);
            log.info("6267调平安回参时间:{}", DateUtil.now());
            String jzbAcceptSeqNo = extenddata.getString("JzbAcceptSeqNo");
            mod.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            mod.setPushTime(DateUtil.now());
            mod.setCnsmrSeqNo(cnsmrSeqNo);
            mod.setOrdersStatus(2);
            sxoSafetyOrderService.updateById(mod);


            LambdaQueryWrapper<SxoPluginsShop> psWrapper = new LambdaQueryWrapper<>();
            psWrapper.eq(SxoPluginsShop::getId, sxoOrder.getShopId());

            SxoPluginsShop sxoPluginsShop = iSxoPluginsShopService.getOne(psWrapper);

            LambdaQueryWrapper<SxoSafetyUser> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(SxoSafetyUser::getUserId, sxoPluginsShop.getUserId());

            SxoSafetyUser safetyUser = sxoSafetyUserService.getOne(userWrapper);

            String freeBalance = safetyUser.getFreezeBalance();

            BigDecimal freeBalanceDecimal = new BigDecimal(freeBalance);

            BigDecimal amountDecimal = new BigDecimal(sxoOrder.getOrderTotalAmt());
            log.info("支付金额："+amountDecimal);

            freeBalanceDecimal = freeBalanceDecimal.add(amountDecimal);
            log.info("冻结增加的金额："+freeBalanceDecimal);

            safetyUser.setFreezeBalance(freeBalanceDecimal.toString());
            sxoSafetyUserService.updateById(safetyUser);

            //冻结充值成功记录交易金额记录
            SxoSafetyAccountRecord sxoSafetyAccountRecord = new SxoSafetyAccountRecord();
            sxoSafetyAccountRecord.setOrderNo(sxoOrder.getTotalOrderNo());
            sxoSafetyAccountRecord.setShopId(sxoOrder.getShopId());
            sxoSafetyAccountRecord.setAmount(sxoOrder.getOrderTotalAmt());
            sxoSafetyAccountRecord.setPendingAmount(freeBalanceDecimal.toString());
            sxoSafetyAccountRecord.setFinalAmount(safetyUser.getBalance());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sxoSafetyAccountRecord.setAddTime(sdf.format(new Date()));
            sxoSafetyAccountRecord.setBusinessType(4);
            sxoSafetyAccountRecord.setChangeType(1);
            sxoSafetyAccountRecord.setReason("下单支付，增加冻结资金");
            sxoSafetyAccountRecordService.save(sxoSafetyAccountRecord);
            vo.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            return vo;
        } catch (Exception e) {
            sxoSafetyOrderService.updateById(mod);
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(),   e.getMessage());
        }
    }

    @Override
    public ThirdFreezeRechargeCancelVo thirdFreezeRechargeCancel(ThirdFreezeRechargeCancelDto dto) {
        if (StrUtil.isEmpty(dto.getOrderId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单id必须填写");
        }
        LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrder::getOrderId, dto.getOrderId());
        queryWrapper.in(SxoSafetyOrder::getOrdersStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getStatus, "0");
        List<SxoSafetyOrder> safetyOrders = sxoSafetyOrderService.list(queryWrapper);
        if (safetyOrders == null) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单ID错误");
        }
        SxoSafetyOrder safetyOrder = safetyOrders.get(0);

        LambdaQueryWrapper<SxoOrderAftersale> qw = new LambdaQueryWrapper<>();
        qw.eq(SxoOrderAftersale::getOrderId, safetyOrder.getOrderId());

        SxoOrderAftersale sxoOrderAftersale = iSxoOrderAftersaleService.getOne(qw);
        return revRegisterBillSupportWithdraw(safetyOrder,sxoOrderAftersale);
    }

    public ThirdFreezeRechargeCancelVo
    revRegisterBillSupportWithdraw(@NotNull SxoSafetyOrder safetyOrder,SxoOrderAftersale sxoOrderAftersale) {
        LambdaQueryWrapper<SxoSafetyOrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(SxoSafetyOrderDetail::getSafetyOrderId, safetyOrder.getId());
        if(sxoOrderAftersale!=null&&sxoOrderAftersale.getGoodsId()!=null){
            qw.eq(SxoSafetyOrderDetail::getGoodsId, sxoOrderAftersale.getGoodsId());

        }

        SxoSafetyOrderDetail orderDetails = sxoSafetyOrderDetailService.getOne(qw);
        if (orderDetails==null) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "冻结充值明细错误");
        }
        ThirdFreezeRechargeCancelVo vo = new ThirdFreezeRechargeCancelVo();

        //分账信息

        List<SxoSafetyOrderRevokeDetail> list = new ArrayList<>();




            List<Map<String, Object>> tranItems = new ArrayList<>();
            JSONObject json = new JSONObject();
            json.put("TxnCode", "KFEJZB6268");
            json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
            String cnsmrSeqNo = PaPayUtil.getCnsmrSeqNo();
            json.put(PaPayUtil.CNSMR_SEQ_NO, cnsmrSeqNo);
            //订单信息
            json.put("PayChannelType", safetyOrder.getPayChannelType());
            json.put("PayChannelAssignMerNo", safetyOrder.getPayChannelAssignMerNo());
            json.put("OldPayOrderDate", safetyOrder.getPayOrderDate());
            json.put("TotalOrderNo", safetyOrder.getTotalOrderNo());//第三方支付渠道产生的支付订单号

            if("1".equals(safetyOrder.getIsFreight())&&safetyOrder.getIncreasePrice()!=null){

                BigDecimal yf = new BigDecimal(safetyOrder.getIncreasePrice());

                BigDecimal result = sxoOrderAftersale.getPrice().subtract(yf);
                json.put("TranTotalAmt", result);


            }else{
                json.put("TranTotalAmt", sxoOrderAftersale.getPrice());
            }

            json.put("OrdersCount", safetyOrder.getOrdersCount());

            Map<String, Object> item = new HashMap<>();

            String subOrderFillCommission = "0";
            String subOrderFillDesc = "退货";
            item.put("SubOrderRefundSubAcctNo", orderDetails.getSubOrderFillSubAcctNo());
            if("1".equals(safetyOrder.getIsFreight())&&safetyOrder.getIncreasePrice()!=null){
                BigDecimal yf = new BigDecimal(safetyOrder.getIncreasePrice());

                BigDecimal result = sxoOrderAftersale.getPrice().subtract(yf);
                item.put("SubOrderRefundAmt", result);
            }else{

                item.put("SubOrderRefundAmt", sxoOrderAftersale.getPrice());
            }

            item.put("SubOrderRefundCommission", subOrderFillCommission);
            item.put("OldPaySubOrderNo", orderDetails.getSubFillOrderNo());
            item.put("SubOrderRefundRemark", subOrderFillDesc);//描述订单的用途
            item.put("SubOrderRefundReservedMsg", "");
            tranItems.add(item);

            json.put("TranItemArray", tranItems);

            SxoSafetyOrderRevoke mod = new SxoSafetyOrderRevoke();

                SxoSafetyOrderRevoke revoke = new SxoSafetyOrderRevoke();
                revoke.setSafetyOrderId(safetyOrder.getId());
                revoke.setUserId(safetyOrder.getUserId());
                revoke.setOrderId(safetyOrder.getOrderId());
                revoke.setOrderNo(safetyOrder.getOrderNo());
                revoke.setShopId(safetyOrder.getShopId());
                revoke.setShopName(safetyOrder.getShopName());
                revoke.setPayChannelType(safetyOrder.getPayChannelType());
                revoke.setPayChannelAssignMerNo(safetyOrder.getPayChannelAssignMerNo());
                revoke.setOldPayOrderDate(safetyOrder.getPayOrderDate());
                revoke.setTotalOrderNo(safetyOrder.getTotalOrderNo());
                revoke.setTranTotalAmt(safetyOrder.getTranTotalAmt());
                revoke.setOrdersCount(safetyOrder.getOrdersCount());
                revoke.setCnsmrSeqNo(cnsmrSeqNo);
                revoke.setStatus(0);
                revoke.setAddTime(DateUtil.now());
                revoke.setUpdTime(DateUtil.now());
                revoke.setRevokeTime(DateUtil.now());


                for (SxoSafetyOrderRevokeDetail detail : list) {
                    detail.setRevokeId(revoke.getId());
                }


                sxoSafetyOrderRevokeService.save(revoke);



            SxoSafetyOrderRevokeDetail revokeDetail = new SxoSafetyOrderRevokeDetail();
            revokeDetail.setSafetyOrderId(orderDetails.getSafetyOrderId());
            revokeDetail.setUserId(safetyOrder.getUserId());
            revokeDetail.setOrderId(safetyOrder.getOrderId());
            revokeDetail.setOrderNo(safetyOrder.getOrderNo());
            revokeDetail.setShopId(safetyOrder.getShopId());
            revokeDetail.setGoodsId(orderDetails.getGoodsId());

            revokeDetail.setSubOrderRefundSubAcctNo(orderDetails.getSubOrderFillSubAcctNo());
            revokeDetail.setSubOrderRefundAmt(orderDetails.getSubOrderFillAmt());
            revokeDetail.setSubOrderRefundCommission(subOrderFillCommission);
            revokeDetail.setOldPaySubOrderNo(orderDetails.getSubFillOrderNo());
            revokeDetail.setSubOrderRefundRemark(subOrderFillDesc);
            revokeDetail.setStatus(0);
            revokeDetail.setAddTime(DateUtil.now());
            revokeDetail.setUpdTime(DateUtil.now());
            list.add(revokeDetail);


            sxoSafetyOrderRevokeDetailService.saveBatch(list);
            mod.setId(revoke.getId());
            mod.setUpdTime(DateUtil.now());
            try {
                IBaseClient baseClient = new ThirdFreezeRechargeCancelApi(sxoSafetyLogService, taskExecutePoolConfig);
                log.info("6268调平安入参："+json);
                log.info("6268调平安入参时间:{}", DateUtil.now());
                HttpResult httpResult = baseClient.execute(json);
                JSONObject extenddata = handleError(httpResult);
                log.info("6268调平安回参："+extenddata);
                log.info("6268调平安回参时间:{}", DateUtil.now());
                String jzbAcceptSeqNo = extenddata.getString("JzbAcceptSeqNo");
                mod.setRevokeStatus(1);
                mod.setJzbAcceptSeqNo(jzbAcceptSeqNo);
                sxoSafetyOrderRevokeService.updateById(mod);

                vo.setJzbAcceptSeqNo(jzbAcceptSeqNo);

            } catch (Exception e) {
                mod.setRevokeStatus(-1);
                mod.setErrorMsg(e.getMessage());
                sxoSafetyOrderRevokeService.updateById(mod);
                throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
            }




        return vo;

    }

    /**
     * 6268退运费
     * @param
     * @return
     */
    public void
    yunfeiFallBack(@NotNull SxoSafetyOrder safetyOrder,SxoOrderAftersale sxoOrderAftersale) {
        LambdaQueryWrapper<SxoOrder> qw = new LambdaQueryWrapper<>();
        qw.eq(SxoOrder::getId, safetyOrder.getOrderId());


        SxoOrder sxoOrder = sxoOrderService.getOne(qw);
        if (sxoOrder==null) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "退款运费找不到订单表数据");
        }

        LambdaQueryWrapper<SxoSafetyOrderDetail> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(SxoSafetyOrderDetail::getSafetyOrderId, safetyOrder.getId());

        if(sxoOrderAftersale!=null&&sxoOrderAftersale.getGoodsId()!=null){
            detailWrapper.eq(SxoSafetyOrderDetail::getGoodsId, sxoOrderAftersale.getGoodsId());

        }
        SxoSafetyOrderDetail orderDetails = sxoSafetyOrderDetailService.getOne(detailWrapper);

        //分账信息

        List<SxoSafetyOrderRevokeDetail> list = new ArrayList<>();




        List<Map<String, Object>> tranItems = new ArrayList<>();
        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6268");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        String cnsmrSeqNo = PaPayUtil.getCnsmrSeqNo();
        json.put(PaPayUtil.CNSMR_SEQ_NO, cnsmrSeqNo);
        //订单信息
        json.put("PayChannelType", safetyOrder.getPayChannelType());
        json.put("PayChannelAssignMerNo", safetyOrder.getPayChannelAssignMerNo());
        json.put("OldPayOrderDate", safetyOrder.getPayOrderDate());
        json.put("TotalOrderNo", safetyOrder.getTotalOrderNo());//第三方支付渠道产生的支付订单号
        json.put("TranTotalAmt", sxoOrder.getFreightfee());
        json.put("OrdersCount", safetyOrder.getOrdersCount());

        Map<String, Object> item = new HashMap<>();

        String subOrderFillCommission = "0";
        String subOrderFillDesc = "退货";
        item.put("SubOrderRefundSubAcctNo", orderDetails.getSubOrderFillSubAcctNo());
        item.put("SubOrderRefundAmt", sxoOrder.getFreightfee());
        item.put("SubOrderRefundCommission", subOrderFillCommission);
        item.put("OldPaySubOrderNo", sxoOrder.getFrozenFreightfeeId());
        item.put("SubOrderRefundRemark", subOrderFillDesc);//描述订单的用途
        item.put("SubOrderRefundReservedMsg", "");
        tranItems.add(item);

        json.put("TranItemArray", tranItems);

        SxoSafetyOrderRevoke mod = new SxoSafetyOrderRevoke();

        SxoSafetyOrderRevoke revoke = new SxoSafetyOrderRevoke();
        revoke.setSafetyOrderId(safetyOrder.getId());
        revoke.setUserId(safetyOrder.getUserId());
        revoke.setOrderId(safetyOrder.getOrderId());
        revoke.setOrderNo(safetyOrder.getOrderNo());
        revoke.setShopId(safetyOrder.getShopId());
        revoke.setShopName(safetyOrder.getShopName());
        revoke.setPayChannelType(safetyOrder.getPayChannelType());
        revoke.setPayChannelAssignMerNo(safetyOrder.getPayChannelAssignMerNo());
        revoke.setOldPayOrderDate(safetyOrder.getPayOrderDate());
        revoke.setTotalOrderNo(safetyOrder.getTotalOrderNo());
        revoke.setTranTotalAmt(safetyOrder.getTranTotalAmt());
        revoke.setOrdersCount(safetyOrder.getOrdersCount());
        revoke.setCnsmrSeqNo(cnsmrSeqNo);
        revoke.setStatus(0);
        revoke.setAddTime(DateUtil.now());
        revoke.setUpdTime(DateUtil.now());
        revoke.setRevokeTime(DateUtil.now());


        for (SxoSafetyOrderRevokeDetail detail : list) {
            detail.setRevokeId(revoke.getId());
        }


        sxoSafetyOrderRevokeService.save(revoke);



        SxoSafetyOrderRevokeDetail revokeDetail = new SxoSafetyOrderRevokeDetail();
        revokeDetail.setSafetyOrderId(orderDetails.getSafetyOrderId());
        revokeDetail.setUserId(safetyOrder.getUserId());
        revokeDetail.setOrderId(safetyOrder.getOrderId());
        revokeDetail.setOrderNo(safetyOrder.getOrderNo());
        revokeDetail.setShopId(safetyOrder.getShopId());
        revokeDetail.setGoodsId(orderDetails.getGoodsId());

        revokeDetail.setSubOrderRefundSubAcctNo(orderDetails.getSubOrderFillSubAcctNo());
        revokeDetail.setSubOrderRefundAmt(orderDetails.getSubOrderFillAmt());
        revokeDetail.setSubOrderRefundCommission(subOrderFillCommission);
        revokeDetail.setOldPaySubOrderNo(orderDetails.getSubFillOrderNo());
        revokeDetail.setSubOrderRefundRemark(subOrderFillDesc);
        revokeDetail.setStatus(0);
        revokeDetail.setAddTime(DateUtil.now());
        revokeDetail.setUpdTime(DateUtil.now());
        list.add(revokeDetail);


        sxoSafetyOrderRevokeDetailService.saveBatch(list);
        mod.setId(revoke.getId());
        mod.setUpdTime(DateUtil.now());
        try {
            IBaseClient baseClient = new ThirdFreezeRechargeCancelApi(sxoSafetyLogService, taskExecutePoolConfig);
            log.info("6268调平安入参："+json);
            log.info("6268调平安入参时间:{}", DateUtil.now());
            HttpResult httpResult = baseClient.execute(json);
            JSONObject extenddata = handleError(httpResult);
            log.info("6268调平安回参："+extenddata);
            log.info("6268调平安回参时间:{}", DateUtil.now());
            String jzbAcceptSeqNo = extenddata.getString("JzbAcceptSeqNo");
            mod.setRevokeStatus(1);
            mod.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            sxoSafetyOrderRevokeService.updateById(mod);


        } catch (Exception e) {
            mod.setRevokeStatus(-1);
            mod.setErrorMsg(e.getMessage());
            sxoSafetyOrderRevokeService.updateById(mod);
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
        }






    }

    @Override
    public SubsidyQuestVo subsidyQuest(SubsidyQuestDto dto) {
        if (StrUtil.isEmpty(dto.getOrderId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单id必须填写");
        }
        LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrder::getOrderId, dto.getOrderId());
        queryWrapper.eq(SxoSafetyOrder::getOrdersStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getStatus, "0");
        List<SxoSafetyOrder> safetyOrders = sxoSafetyOrderService.list(queryWrapper);
        if (safetyOrders.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单ID错误");
        }
        SxoSafetyOrder safetyOrder = safetyOrders.get(0);
        LambdaQueryWrapper<SxoSafetyOrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(SxoSafetyOrderDetail::getSafetyOrderId, safetyOrder.getId());
        List<SxoSafetyOrderDetail> orderDetails = sxoSafetyOrderDetailService.list(qw);
        if (orderDetails.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "冻结充值明细错误");
        }
        String subsidyOrderNo = TradetraceUtil.buildTradetraceSubsidy();
        SxoSafetyOrderDetail orderDetail = orderDetails.get(0);
        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6269");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        String cnsmrSeqNo = PaPayUtil.getCnsmrSeqNo();
        json.put(PaPayUtil.CNSMR_SEQ_NO, cnsmrSeqNo);
        //订单信息
        String oldPaySubOrderNo = orderDetail.getSubFillOrderNo();
        String oldPayOrderDate = safetyOrder.getPayOrderDate();
        json.put("OldPaySubOrderNo", oldPaySubOrderNo);
        json.put("OldPayOrderDate", oldPayOrderDate);
        json.put("SubsidyOrderNo", subsidyOrderNo);
        json.put("SubsidyOutSubAcctNo", payConfig.getSubAcctNo13());
        json.put("SubsidyInSubAcctNo", dto.getSubsidyInSubAcctNo());
        json.put("SubsidyAmt", dto.getSubsidyAmt());
        json.put("SubsidyOrderDesc", "补贴");
        json.put("SubsidyRemark", "");

        SxoSafetyOrderSubsidy subsidyOrderSubsidy = new SxoSafetyOrderSubsidy();
        subsidyOrderSubsidy.setUserId(safetyOrder.getUserId());
        subsidyOrderSubsidy.setSafetyOrderId(safetyOrder.getId());
        subsidyOrderSubsidy.setOrderId(safetyOrder.getOrderId());
        subsidyOrderSubsidy.setOrderNo(safetyOrder.getOrderNo());
        subsidyOrderSubsidy.setShopId(safetyOrder.getShopId());
        subsidyOrderSubsidy.setOldPaySubOrderNo(oldPaySubOrderNo);
        subsidyOrderSubsidy.setOldPayOrderDate(oldPayOrderDate);
        subsidyOrderSubsidy.setSubsidyOrderNo(subsidyOrderNo);
        subsidyOrderSubsidy.setSubsidyOutSubAcctNo(payConfig.getSubAcctNo13());
        subsidyOrderSubsidy.setSubsidyInSubAcctNo(dto.getSubsidyInSubAcctNo());
        subsidyOrderSubsidy.setSubsidyAmt(dto.getSubsidyAmt());
        subsidyOrderSubsidy.setSubsidyOrderDesc("补贴");
        subsidyOrderSubsidy.setStatus(0);
        subsidyOrderSubsidy.setAddTime(DateUtil.now());
        subsidyOrderSubsidy.setUpdTime(DateUtil.now());
        sxoSafetyOrderSubsidyService.save(subsidyOrderSubsidy);


        try {
            IBaseClient baseClient = new SubsidyQuestApi(sxoSafetyLogService, taskExecutePoolConfig);
            log.info("6269调平安入参："+json);
            log.info("6269调平安入参时间:{}", DateUtil.now());
            HttpResult httpResult = baseClient.execute(json);
            JSONObject extenddata = handleError(httpResult);
            log.info("6269调平安回参："+json);
            log.info("6269调平安回参时间:{}", DateUtil.now());
            String jzbAcceptSeqNo = extenddata.getString("JzbAcceptSeqNo");

            String date = DateUtil.now();
            SxoSafetyOrderSubsidy mod = new SxoSafetyOrderSubsidy();
            mod.setId(subsidyOrderSubsidy.getId());
            mod.setSubsidyStatus(3);
            mod.setSubsidyTime(date);
            mod.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            mod.setCnsmrSeqNo(cnsmrSeqNo);
            mod.setErrorMsg("");
            sxoSafetyOrderSubsidyService.updateById(mod);

            SubsidyQuestVo vo = new SubsidyQuestVo();
            vo.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            return vo;
        } catch (Exception e) {
            SxoSafetyOrderSubsidy mod = new SxoSafetyOrderSubsidy();
            mod.setId(subsidyOrderSubsidy.getId());
            mod.setUpdTime(DateUtil.now());
            mod.setErrorMsg(e.getMessage());
            sxoSafetyOrderSubsidyService.updateById(mod);
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
        }

    }

    @Override
    public SubsidyQuestVo  subsidyCancel(SubsidyQuestDto dto) {
        if (StrUtil.isEmpty(dto.getOrderId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单id必须填写");
        }
        LambdaQueryWrapper<SxoSafetyOrderSubsidy> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrderSubsidy::getOrderId, dto.getOrderId());
        queryWrapper.eq(SxoSafetyOrderSubsidy::getSubsidyStatus, "1");
        queryWrapper.eq(SxoSafetyOrderSubsidy::getStatus, "0");
        List<SxoSafetyOrderSubsidy> safetyOrders = sxoSafetyOrderSubsidyService.list(queryWrapper);
        if (safetyOrders.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单ID错误");
        }
        SxoSafetyOrderSubsidy subsidy = safetyOrders.get(0);


        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6270");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        //订单信息
        json.put("OldPaySubOrderNo", subsidy.getOldPaySubOrderNo());
        json.put("OldPayOrderDate", subsidy.getOldPayOrderDate());
        json.put("OldSubsidyOrderNo", subsidy.getSubsidyOrderNo());
        json.put("OldSubsidyOutSubAcctNo", subsidy.getSubsidyOutSubAcctNo());
        json.put("OldSubsidyInSubAcctNo", subsidy.getSubsidyInSubAcctNo());
        json.put("SubsidyCancelAmt", subsidy.getSubsidyAmt());
        json.put("SubsidyCancelRemark", "补贴撤销");


        try {
            IBaseClient baseClient = new SubsidyCancelApi(sxoSafetyLogService, taskExecutePoolConfig);
            log.info("6270调平安入参："+json);
            log.info("6270调平安入参时间:{}", DateUtil.now());
            HttpResult httpResult = baseClient.execute(json);
            JSONObject extenddata = handleError(httpResult);
            log.info("6270调平安回参："+json);
            log.info("6270调平安回参时间:{}", DateUtil.now());
            String jzbAcceptSeqNo = extenddata.getString("JzbAcceptSeqNo");

            String date = DateUtil.now();
            SxoSafetyOrderSubsidy mod = new SxoSafetyOrderSubsidy();
            mod.setId(subsidy.getId());
            mod.setSubsidyStatus(2);
            mod.setSubsidyTime(date);
            mod.setUpdTime(date);
            mod.setJzbAcceptRevNo(jzbAcceptSeqNo);
            mod.setRevCnsmrSeqNo(extenddata.getString(PaPayUtil.CNSMR_SEQ_NO));
            mod.setErrorMsg("");
            sxoSafetyOrderSubsidyService.updateById(mod);


            SubsidyQuestVo vo = new SubsidyQuestVo();
            vo.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            return vo;
        } catch (Exception e) {
            SxoSafetyOrderSubsidy mod = new SxoSafetyOrderSubsidy();
            mod.setId(subsidy.getId());
            mod.setUpdTime(DateUtil.now());
            mod.setErrorMsg("撤销:" + e.getMessage());
            sxoSafetyOrderSubsidyService.updateById(mod);
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
        }

    }

    @Override
    public SubAccountQuestVo subAccountQuest(SubAccountQuestDto dto) {

        SubAccountQuestVo vo = new SubAccountQuestVo();

        log.info("商户确认收货php调java的分账开始:");
        if (StrUtil.isEmpty(dto.getOrderId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单id必须填写");
        }
        LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrder::getOrderId, dto.getOrderId());
        queryWrapper.eq(SxoSafetyOrder::getOrdersStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getSepStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getClearStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getStatus, "0");
        List<SxoSafetyOrder> safetyOrders = sxoSafetyOrderService.list(queryWrapper);
        if (safetyOrders.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单ID错误");
        }
        SxoSafetyOrder safetyOrder = safetyOrders.get(0);
        LambdaQueryWrapper<SxoSafetyOrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(SxoSafetyOrderDetail::getSafetyOrderId, safetyOrder.getId());
        List<SxoSafetyOrderDetail> orderDetails = sxoSafetyOrderDetailService.list(qw);
        if (orderDetails.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "冻结充值明细错误");
        }

        for(SxoSafetyOrderDetail orderDetail :orderDetails){

            JSONObject json = new JSONObject();
            json.put("TxnCode", "KFEJZB6271");
            json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());

            String cnsmrSeqNo = PaPayUtil.getCnsmrSeqNo();
            json.put(PaPayUtil.CNSMR_SEQ_NO, cnsmrSeqNo);
            //订单信息
            String outSubAcctNo = orderDetail.getSubOrderFillSubAcctNo();
            String oldPaySubOrderNo = orderDetail.getSubFillOrderNo();
            String oldPayOrderDate = safetyOrder.getPayOrderDate();
            json.put("OldPaySubOrderNo", oldPaySubOrderNo);
            json.put("OldPayOrderDate", oldPayOrderDate);
            json.put("OutSubAcctNo", outSubAcctNo);
            json.put("TranTotalAmt", orderDetail.getSubOrderFillAmt());


            SxoSafetySepAcc sepAcc = new SxoSafetySepAcc();
            sepAcc.setUserId(safetyOrder.getUserId());
            sepAcc.setSafetyOrderId(safetyOrder.getId());
            sepAcc.setOrderId(safetyOrder.getOrderId());
            sepAcc.setOrderNo(safetyOrder.getOrderNo());
            sepAcc.setShopId(safetyOrder.getShopId());
            sepAcc.setShopName(safetyOrder.getShopName());
            sepAcc.setOldPaySubOrderNo(oldPaySubOrderNo);
            sepAcc.setOldPayOrderDate(oldPayOrderDate);
            sepAcc.setOrderMonth(safetyOrder.getOrderMonth());
            sepAcc.setOutSubAcctNo(outSubAcctNo);
            sepAcc.setTranTotalAmt(orderDetail.getSubOrderFillAmt());
            sepAcc.setPlatTotalAmt(safetyOrder.getPlatTotalAmt());
            sepAcc.setIncreasePrice(safetyOrder.getIncreasePrice());
            sepAcc.setSepStatus(1);
            sepAcc.setStatus(0);
            sepAcc.setAddTime(DateUtil.now());
            sepAcc.setUpdTime(DateUtil.now());

            List<Map<String, String>> list = new ArrayList<>();

            String subAcctOrderNo = TradetraceUtil.buildTradetraceAcc();
            String subAcctAmt = orderDetail.getAcctAmt();
            String subAcctOrderDesc = "分账";
            Map<String, String> item = new HashMap<>();
            item.put("SubAcctOrderNo", subAcctOrderNo);
            item.put("InSubAcctNo", outSubAcctNo);
            item.put("SubAcctAmt", subAcctAmt);
            item.put("SubAcctOrderDesc", subAcctOrderDesc);
            item.put("SubAcctRemark", "订单分账商家金额");
            list.add(item);

            String subAcctOrderNo1 = TradetraceUtil.buildTradetraceAccSer();
            String subAcctAmt1 = orderDetail.getSerAcctAmt();
            Map<String, String> item1 = new HashMap<>();
            item1.put("SubAcctOrderNo", subAcctOrderNo1);
            item1.put("InSubAcctNo", payConfig.getSubAcctNo3());
            item1.put("SubAcctAmt", subAcctAmt1);
            item1.put("SubAcctOrderDesc", subAcctOrderDesc);
            item1.put("SubAcctRemark", "订单分账平台金额");
            list.add(item1);

            json.put("TranItemArray", list);

            int ordersCount = list.size();
            json.put("OrdersCount", ordersCount);
            sepAcc.setOrdersCount(String.valueOf(ordersCount));
            sxoSafetySepAccService.save(sepAcc);
            List<SxoSafetySepAccDetail> details = new ArrayList<>();
            for (Map<String, String> map : list) {
                SxoSafetySepAccDetail sepAccDetail = new SxoSafetySepAccDetail();
                sepAccDetail.setSepAccId(sepAcc.getId());
                sepAccDetail.setSubAcctOrderNo(map.get("SubAcctOrderNo"));
                sepAccDetail.setInSubAcctNo(map.get("InSubAcctNo"));
                sepAccDetail.setSubAcctAmt(map.get("SubAcctAmt"));
                sepAccDetail.setSubAcctOrderDesc(map.get("SubAcctOrderDesc"));
                sepAccDetail.setSubAcctRemark(map.get("SubAcctRemark"));
                sepAccDetail.setSubAccType("0");
                if (map.get("InSubAcctNo").equals(payConfig.getSubAcctNo3())) {
                    sepAccDetail.setSubAccType("1");
                }
                details.add(sepAccDetail);
            }
            sxoSafetySepAccDetailService.saveBatch(details);


            try {
                IBaseClient baseClient = new SubAccountQuestApi(sxoSafetyLogService, taskExecutePoolConfig);
                log.info("6271调平安入参："+json);
                log.info("6271调平安入参时间:{}", DateUtil.now());
                HttpResult httpResult = baseClient.execute(json);
                JSONObject extenddata = handleError(httpResult);
                log.info("6271调平安回参："+extenddata);
                log.info("6271调平安回参时间:{}", DateUtil.now());
                String jzbAcceptSeqNo = extenddata.getString("JzbAcceptSeqNo");

                String date = DateUtil.now();
                SxoSafetySepAcc mod = new SxoSafetySepAcc();
                mod.setId(sepAcc.getId());
                mod.setSepStatus(1);//分账状态有问题
                mod.setSepTime(date);
                mod.setCnsmrSeqNo(cnsmrSeqNo);
                mod.setJzbAcceptSeqNo(jzbAcceptSeqNo);
                sxoSafetySepAccService.updateById(mod);

                SxoSafetyOrder order = new SxoSafetyOrder();
                order.setId(safetyOrder.getId());
                order.setSepStatus(2);
                order.setSepTime(date);
                order.setOrderSettleStatus(1);
                sxoSafetyOrderService.updateById(order);

                //对用户金额进行操作，先通过orderid查plugin——shop的userid再去获取safery-user的金额

                LambdaQueryWrapper<SxoPluginsShop> psWrapper = new LambdaQueryWrapper<>();
                psWrapper.eq(SxoPluginsShop::getId, safetyOrder.getShopId());

                SxoPluginsShop sxoPluginsShop = iSxoPluginsShopService.getOne(psWrapper);

                LambdaQueryWrapper<SxoSafetyUser> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.eq(SxoSafetyUser::getUserId, sxoPluginsShop.getUserId());

                SxoSafetyUser safetyUser = sxoSafetyUserService.getOne(userWrapper);

                String balance = safetyUser.getBalance();
                String freeBalance = safetyUser.getFreezeBalance();

                BigDecimal balanDecimal = new BigDecimal(balance);

                BigDecimal freeBalanceDecimal = new BigDecimal(freeBalance);


                //分账成功记录交易金额记录
                SxoSafetyAccountRecord sxoSafetyAccountRecord1 = new SxoSafetyAccountRecord();
                sxoSafetyAccountRecord1.setOrderNo(safetyOrder.getTotalOrderNo());
                sxoSafetyAccountRecord1.setShopId(safetyOrder.getShopId());
                sxoSafetyAccountRecord1.setAmount(safetyOrder.getOrderTotalAmt());


                sxoSafetyAccountRecord1.setFinalAmount(balance);
                BigDecimal amount = new BigDecimal(safetyOrder.getOrderTotalAmt());
                freeBalanceDecimal = freeBalanceDecimal.subtract(amount);
                sxoSafetyAccountRecord1.setPendingAmount(freeBalanceDecimal.toString());
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sxoSafetyAccountRecord1.setAddTime(sdf1.format(new Date()));
                sxoSafetyAccountRecord1.setBusinessType(3);
                sxoSafetyAccountRecord1.setChangeType(2);
                sxoSafetyAccountRecord1.setReason("资金解冻，转出金额");
                sxoSafetyAccountRecordService.save(sxoSafetyAccountRecord1);

                //分账成功记录交易金额记录
                SxoSafetyAccountRecord sxoSafetyAccountRecord2 = new SxoSafetyAccountRecord();
                sxoSafetyAccountRecord2.setOrderNo(safetyOrder.getTotalOrderNo());
                sxoSafetyAccountRecord2.setShopId(safetyOrder.getShopId());
                sxoSafetyAccountRecord2.setAmount(safetyOrder.getOrderTotalAmt());
                sxoSafetyAccountRecord2.setPendingAmount(freeBalanceDecimal.toString());
                balanDecimal = balanDecimal.add(amount);
                sxoSafetyAccountRecord2.setFinalAmount(balanDecimal.toString());
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sxoSafetyAccountRecord2.setAddTime(sdf2.format(new Date()));
                sxoSafetyAccountRecord2.setBusinessType(3);
                sxoSafetyAccountRecord2.setChangeType(1);
                sxoSafetyAccountRecord2.setReason("资金结算入账");
                sxoSafetyAccountRecordService.save(sxoSafetyAccountRecord2);


                //分账成功记录交易金额记录
                SxoSafetyAccountRecord sxoSafetyAccountRecord3 = new SxoSafetyAccountRecord();
                sxoSafetyAccountRecord3.setOrderNo(safetyOrder.getTotalOrderNo());
                sxoSafetyAccountRecord3.setShopId(safetyOrder.getShopId());
                sxoSafetyAccountRecord3.setAmount(subAcctAmt1);
                sxoSafetyAccountRecord3.setPendingAmount(freeBalanceDecimal.toString());
                BigDecimal fwf = new BigDecimal(subAcctAmt1);
                balanDecimal = balanDecimal.subtract(fwf);
                sxoSafetyAccountRecord3.setFinalAmount(balanDecimal.toString());
                SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sxoSafetyAccountRecord3.setAddTime(sdf3.format(new Date()));
                sxoSafetyAccountRecord3.setBusinessType(2);
                sxoSafetyAccountRecord3.setChangeType(2);
                sxoSafetyAccountRecord3.setReason("商品交易服务费");
                sxoSafetyAccountRecordService.save(sxoSafetyAccountRecord3);


                safetyUser.setBalance(balanDecimal.toString());
                safetyUser.setFreezeBalance(freeBalanceDecimal.toString());
                sxoSafetyUserService.updateById(safetyUser);


                vo.setJzbAcceptSeqNo(jzbAcceptSeqNo);
                return vo;
            } catch (Exception e) {
                SxoSafetySepAcc mod = new SxoSafetySepAcc();
                mod.setId(sepAcc.getId());
                mod.setUpdTime(DateUtil.now());
                mod.setSepStatus(-1);
                mod.setErrorMsg(e.getMessage());
                sxoSafetySepAccService.updateById(mod);
                throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
            }
        }

        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ThirdFreezeRechargeCancelVo orderRefund(ThirdFreezeRechargeCancelDto dto) {

        log.info("订单退款执行开始；时间:{}", DateUtil.now());
        if (StrUtil.isEmpty(dto.getOrderId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单id必须填写");
        }
        LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrder::getOrderId, dto.getOrderId());
        queryWrapper.in(SxoSafetyOrder::getOrdersStatus, "0", "2");
        queryWrapper.eq(SxoSafetyOrder::getStatus, "0");
        List<SxoSafetyOrder> safetyOrders = sxoSafetyOrderService.list(queryWrapper);
        if (safetyOrders.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "分账未找到需要撤销订单");
        }



        LambdaQueryWrapper<SxoOrderAftersale> saleWrapper = new LambdaQueryWrapper<>();
        saleWrapper.eq(SxoOrderAftersale::getId, dto.getSaleId());

        SxoOrderAftersale sxoOrderAftersale =   iSxoOrderAftersaleService.getOne(saleWrapper);


        SxoSafetyOrder safetyOrder = safetyOrders.get(0);
        LambdaQueryWrapper<SxoSafetySepAcc> accWrapper = new LambdaQueryWrapper<>();
        accWrapper.eq(SxoSafetySepAcc::getOrderId, safetyOrder.getOrderId());
        accWrapper.eq(SxoSafetySepAcc::getSafetyOrderId, safetyOrder.getId());
        accWrapper.in(SxoSafetySepAcc::getSepStatus, "1", "3");
        accWrapper.eq(SxoSafetySepAcc::getStatus, "0");
        List<SxoSafetySepAcc> accs = sxoSafetySepAccService.list(accWrapper);
        //未分账直接撤销充值
        if (accs.isEmpty()) {

            //判断是否需要退运费
            if("1".equals(dto.getIsFreight())){

                yunfeiFallBack(safetyOrder,sxoOrderAftersale);
                safetyOrder.setIsFreight("1");

            }
            ThirdFreezeRechargeCancelVo vo = revRegisterBillSupportWithdraw(safetyOrder,sxoOrderAftersale);
            if (vo != null) {
                SxoSafetyOrder mod = new SxoSafetyOrder();
                mod.setId(safetyOrder.getId());
                mod.setUpdTime(DateUtil.now());
                mod.setRevokeTime(DateUtil.now());
                mod.setRevokeStatus(2);
                mod.setOrderSettleStatus(2);
                mod.setSaleId(dto.getSaleId());
                sxoSafetyOrderService.updateById(mod);
            }
            return vo;
        }
        ThirdFreezeRechargeCancelVo vo = new ThirdFreezeRechargeCancelVo();
        List<SxoSafetySepAcc> sepStatus1 = accs.stream().filter(a -> a.getSepStatus().equals(1)).toList();
        List<SxoSafetySepAcc> sepStatus3 = accs.stream().filter(a -> a.getSepStatus().equals(3)).toList();
        //1分账成功
        if (!sepStatus1.isEmpty()) {


            SxoSafetyOrder modO = new SxoSafetyOrder();
            if("1".equals(dto.getIsFreight())){

                yunfeiFallBack(safetyOrder,sxoOrderAftersale);
                modO.setIsFreight("1");

            }

            SubAccountQuestDto subAccountQuestDto = new SubAccountQuestDto();
            subAccountQuestDto.setSepAccId(sepStatus1.get(0).getId());
            subAccountCancel(subAccountQuestDto);
            String date = DateUtil.now();
            SxoSafetySepAcc mod = new SxoSafetySepAcc();
            mod.setId(sepStatus1.get(0).getId());
            mod.setUpdTime(DateUtil.now());
            mod.setNeedRevoke(1);
            mod.setSepRevokeTime(date);
            mod.setUpdTime(date);
            mod.setSaleId(dto.getSaleId());


            modO.setId(safetyOrder.getId());
            modO.setUpdTime(DateUtil.now());
            modO.setRevokeTime(DateUtil.now());
            modO.setRevokeStatus(2);
            modO.setOrderSettleStatus(2);
            modO.setSaleId(dto.getSaleId());
            sxoSafetyOrderService.updateById(modO);

            sxoSafetySepAccService.updateById(mod);
        }
        //3分账中
        if (!sepStatus3.isEmpty()) {
            String date = DateUtil.now();
            SxoSafetySepAcc mod = new SxoSafetySepAcc();
            mod.setId(sepStatus3.get(0).getId());
            mod.setUpdTime(DateUtil.now());
            mod.setNeedRevoke(0);
            mod.setSaleId(dto.getSaleId());
            mod.setUpdTime(date);
            sxoSafetySepAccService.updateById(mod);
        }
        return vo;
    }

    @Override
    public void
    orderRefundToPhp(ThirdFreezeRechargeCancelDto dto) {
        try {
            Map<String, String> bodys = new HashMap<>();
            bodys.put("id", dto.getSaleId());
            HttpResponse response = HttpUtil.doPost(payConfig.getPhpUrl(), "?s=java.refund/goRef", null, null, bodys);
            if (response.getStatusLine().getStatusCode() == 200) {
                String body = EntityUtils.toString(response.getEntity());
                log.info("订单{}撤销推送PHP成功:{}", dto.getSaleId(),body);

                //php退款成功记录退款金额日志

                LambdaQueryWrapper<SxoOrderAftersale> saleWrapper = new LambdaQueryWrapper<>();
                saleWrapper.eq(SxoOrderAftersale::getId, dto.getSaleId());

                SxoOrderAftersale sxoOrderAftersale = iSxoOrderAftersaleService.getOne(saleWrapper);


                LambdaQueryWrapper<SxoSafetyOrder> orderWrapper = new LambdaQueryWrapper<>();
                orderWrapper.eq(SxoSafetyOrder::getOrderId, sxoOrderAftersale.getOrderId());

                SxoSafetyOrder safetyOrder = sxoSafetyOrderService.getOne(orderWrapper);

                LambdaQueryWrapper<SxoPluginsShop> psWrapper = new LambdaQueryWrapper<>();
                psWrapper.eq(SxoPluginsShop::getId, safetyOrder.getShopId());

                SxoPluginsShop sxoPluginsShop = iSxoPluginsShopService.getOne(psWrapper);
                LambdaQueryWrapper<SxoSafetyUser> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.eq(SxoSafetyUser::getUserId, sxoPluginsShop.getUserId());
                SxoSafetyUser safetyUser = sxoSafetyUserService.getOne(userWrapper);
                String freeBalance = safetyUser.getFreezeBalance();
                BigDecimal freeBalanceDecimal = new BigDecimal(freeBalance);

                String Balance = safetyUser.getBalance();
                BigDecimal BalanceDecimal = new BigDecimal(Balance);

                LambdaQueryWrapper<SxoSafetySepAcc> orderAccWrapper = new LambdaQueryWrapper<>();
                orderAccWrapper.eq(SxoSafetySepAcc::getOrderId, sxoOrderAftersale.getOrderId());
                //分账状态（-1:分账失败；0：未分账;1：分账成功；2:分账撤销） 分账成功和分账撤销都表示该笔是分账的类型
                orderAccWrapper.in(SxoSafetySepAcc::getSepStatus, "1", "2");
                SxoSafetySepAcc sxoSafetySepAcc = sxoSafetySepAccService.getOne(orderAccWrapper);

                //冻结充值成功记录交易金额记录
                SxoSafetyAccountRecord sxoSafetyAccountRecord = new SxoSafetyAccountRecord();
                sxoSafetyAccountRecord.setOrderNo(safetyOrder.getTotalOrderNo());
                sxoSafetyAccountRecord.setShopId(safetyOrder.getShopId());
                sxoSafetyAccountRecord.setAmount(safetyOrder.getOrderTotalAmt());

                if(sxoSafetySepAcc!=null){

                    log.info("分账的情况：可提现余额减去退款供应商金额，冻结金额保持不变");
                    BigDecimal acctamtDecimal = new BigDecimal(safetyOrder.getTotalAcctAmt());
                    BalanceDecimal = BalanceDecimal.subtract(acctamtDecimal);

                    BigDecimal orderTotalAmt = new BigDecimal(safetyOrder.getOrderTotalAmt());
                    sxoSafetyAccountRecord.setFinalAmount(BalanceDecimal.toString());
//                    log.info("分账前冻结金额："+freeBalanceDecimal);
//                    freeBalanceDecimal = freeBalanceDecimal.add(orderTotalAmt);
                    log.info("分账后冻结金额："+freeBalanceDecimal);
                    sxoSafetyAccountRecord.setPendingAmount(freeBalanceDecimal.toString());
                    safetyUser.setBalance(BalanceDecimal.toString());
//                    safetyUser.setFreezeBalance(freeBalanceDecimal.toString());

                }else{
                    log.info("不分账的情况：冻结金额减去退款金额，可提现余额保持不变");
                    sxoSafetyAccountRecord.setFinalAmount(Balance);
                    BigDecimal acctamtDecimal = new BigDecimal(safetyOrder.getOrderTotalAmt());
                    log.info("不分账前冻结金额："+freeBalanceDecimal);
                    freeBalanceDecimal = freeBalanceDecimal.subtract(acctamtDecimal);
                    log.info("不分账后冻结金额："+freeBalanceDecimal);
                    safetyUser.setFreezeBalance(freeBalanceDecimal.toString());
                    sxoSafetyAccountRecord.setPendingAmount(freeBalanceDecimal.toString());
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sxoSafetyAccountRecord.setAddTime(sdf.format(new Date()));
                sxoSafetyAccountRecord.setBusinessType(6);
                sxoSafetyAccountRecord.setChangeType(2);
                sxoSafetyAccountRecord.setReason("订单退款");
                sxoSafetyAccountRecordService.save(sxoSafetyAccountRecord);

                sxoSafetyUserService.updateById(safetyUser);


            } else {
                log.error("订单撤销推送PHP失败:{}", response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("订单撤销推送PHP失败异常:{}", e.getMessage());
        }

    }

    @Override
    public SubAccountQuestVo subAccountCancel(SubAccountQuestDto dto) {
        SxoSafetySepAcc sepAcc = sxoSafetySepAccService.getById(dto.getSepAccId());
        if (sepAcc == null) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "分账ID错误");
        }
        LambdaQueryWrapper<SxoSafetySepAccDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(SxoSafetySepAccDetail::getSepAccId, sepAcc.getId());
        List<SxoSafetySepAccDetail> sepAccDetails = sxoSafetySepAccDetailService.list(qw);
        if (sepAccDetails.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "分账明细错误");
        }
        String date = DateUtil.now();

        String cnsmrSeqNo = PaPayUtil.getCnsmrSeqNo();
        SxoSafetySepAccRevoke accRevoke = new SxoSafetySepAccRevoke();
        accRevoke.setUserId(sepAcc.getUserId());
        accRevoke.setOrderId(sepAcc.getOrderId());
        accRevoke.setOrderNo(sepAcc.getOrderNo());
        accRevoke.setShopId(sepAcc.getShopId());
        accRevoke.setShopName(sepAcc.getShopName());
        accRevoke.setSepAccId(sepAcc.getId());
        accRevoke.setOldPaySubOrderNo(sepAcc.getOldPaySubOrderNo());
        accRevoke.setOldPayOrderDate(sepAcc.getOldPayOrderDate());
        accRevoke.setOutSubAcctNo(sepAcc.getOutSubAcctNo());
        accRevoke.setTranTotalAmt(sepAcc.getTranTotalAmt());
        accRevoke.setOrdersCount(sepAcc.getOrdersCount());
        accRevoke.setStatus(0);
        accRevoke.setSepStatus(1);
        accRevoke.setSepRevokeTime(date);
        accRevoke.setCnsmrSeqNo(cnsmrSeqNo);
        accRevoke.setAddTime(date);
        accRevoke.setUpdTime(date);
        accRevoke.setSaleId(dto.getSaleId());


        List<SxoSafetySepAccRevokeDetail> accRevokeDetails = new ArrayList<>();

        for (SxoSafetySepAccDetail detail : sepAccDetails) {
            SxoSafetySepAccRevokeDetail accRevokeDetail = new SxoSafetySepAccRevokeDetail();
            accRevokeDetail.setSepAccRevokeId(accRevoke.getId());
            accRevokeDetail.setSepAccDetailId(detail.getId());
            accRevokeDetail.setOldSubOrderNo(detail.getSubAcctOrderNo());
            accRevokeDetail.setOldInSubAcctNo(detail.getInSubAcctNo());
            accRevokeDetail.setSubAcctCancelAmt(detail.getSubAcctAmt());
            accRevokeDetail.setSubAcctCancelRemark("分账撤销");
            accRevokeDetails.add(accRevokeDetail);
        }

        sxoSafetySepAccRevokeService.save(accRevoke);
        for (SxoSafetySepAccRevokeDetail detail : accRevokeDetails) {
            detail.setSepAccRevokeId(accRevoke.getId());
        }
        sxoSafetySepAccRevokeDetailService.saveBatch(accRevokeDetails);

        for (SxoSafetySepAccRevokeDetail detail : accRevokeDetails) {
            SxoSafetySepAccRevokeDetail mod = new SxoSafetySepAccRevokeDetail();
            mod.setId(detail.getId());
            try {
                JSONObject json = new JSONObject();
                json.put("TxnCode", "KFEJZB6272");
                json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
                cnsmrSeqNo = PaPayUtil.getCnsmrSeqNo();
                json.put(PaPayUtil.CNSMR_SEQ_NO, cnsmrSeqNo);
                json.put("OldPaySubOrderNo", sepAcc.getOldPaySubOrderNo());
                json.put("OldPayOrderDate", sepAcc.getOldPayOrderDate());
                json.put("OldOutSubAcctNo", sepAcc.getOutSubAcctNo());
                json.put("TranTotalAmt", detail.getSubAcctCancelAmt());
                json.put("OrdersCount", 1);

                List<Map<String, String>> list = new ArrayList<>();
                Map<String, String> map = new HashMap<>();
                map.put("OldSubOrderNo", detail.getOldSubOrderNo());
                map.put("OldInSubAcctNo", detail.getOldInSubAcctNo());
                map.put("SubAcctCancelAmt", detail.getSubAcctCancelAmt());
                map.put("SubAcctCancelRemark", detail.getSubAcctCancelRemark());
                list.add(map);
//                Map<String, String> map1 = new HashMap<>();
//                map1.put("OldSubOrderNo", detail.getOldSubOrderNo());
//                map1.put("OldInSubAcctNo", payConfig.getSubAcctNo());
//                map1.put("SubAcctCancelAmt", detail.getSubAcctCancelAmt());
//                map1.put("SubAcctCancelRemark", detail.getSubAcctCancelRemark());
//                list.add(map1);
                json.put("TranItemArray", list);

                IBaseClient baseClient = new SubAccountCancelApi(sxoSafetyLogService, taskExecutePoolConfig);
                log.info("6272调平安入参："+json);
                log.info("6272调平安入参时间:{}", DateUtil.now());
                HttpResult httpResult = baseClient.execute(json);
                JSONObject extenddata = handleError(httpResult);
                log.info("6272调平安回参："+extenddata);
                log.info("6272调平安回参时间:{}", DateUtil.now());
                String jzbAcceptSeqNo1 = extenddata.getString("JzbAcceptSeqNo");
                mod.setCnsmrSeqNo(cnsmrSeqNo);
                mod.setSepRevokeTime(date);
                mod.setJzbAcceptSeqNo(jzbAcceptSeqNo1);
                mod.setSepStatus(1);
                sxoSafetySepAccRevokeDetailService.updateById(mod);

            } catch (Exception e) {
                mod.setSepStatus(-1);
                mod.setErrorMsg(e.getMessage());
                sxoSafetySepAccRevokeDetailService.updateById(mod);
            }

        }

        SubAccountQuestVo vo = new SubAccountQuestVo();
        vo.setJzbAcceptSeqNo("");
        return vo;
    }


    @Override
    public RegisterBillSupportWithdrawVo registerBillSupportWithdraw(RegisterBillSupportWithdrawDto dto) {
      /*  if (StrUtil.isEmpty(dto.getOrderId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单id必须填写");
        }
        if (StrUtil.isEmpty(dto.getSuspendAmt())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "挂账金额必须填写");
        }*/
      /*  LambdaQueryWrapper<SxoSafetyOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyOrder::getOrderId, dto.getOrderId());
        queryWrapper.eq(SxoSafetyOrder::getOrdersStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getRevokeStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getSepStatus, "0");
        queryWrapper.eq(SxoSafetyOrder::getStatus, "0");
        List<SxoSafetyOrder> safetyOrders = sxoSafetyOrderService.list(queryWrapper);
        if (safetyOrders.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "订单ID错误");
        }
        SxoSafetyOrder safetyOrder = safetyOrders.get(0);
        LambdaQueryWrapper<SxoSafetyOrderDetail> qw = new LambdaQueryWrapper<>();
        qw.eq(SxoSafetyOrderDetail::getSafetyOrderId, safetyOrder.getId());
        List<SxoSafetyOrderDetail> orderDetails = sxoSafetyOrderDetailService.list(qw);
        if (orderDetails.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "冻结充值明细错误");
        }

        SxoSafetyOrderDetail orderDetail = orderDetails.get(0);*/
        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6139");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        //订单信息
        String subAcctNo = dto.getSubAcctNo();
        String orderNo = TradetraceUtil.buildTradetraceAccReg();
        String tranFee = StrUtil.isEmpty(dto.getTranFee()) ? "0" : dto.getTranFee();
        String suspendAmt = dto.getSuspendAmt();
        json.put("SubAcctNo", subAcctNo);
        json.put("TranNetMemberCode", dto.getTranNetMemberCode());
        json.put("OrderNo", orderNo);
        json.put("SuspendAmt", suspendAmt);
        json.put("TranFee", tranFee);


        SxoSafetyRegCredit sepAcc = new SxoSafetyRegCredit();
        //sepAcc.setUserId(safetyOrder.getUserId());
        //sepAcc.setSafetyOrderId(safetyOrder.getId());
        //sepAcc.setOrderId(safetyOrder.getOrderId());
        //sepAcc.setOrderNo(safetyOrder.getOrderNo());
        //sepAcc.setShopId(safetyOrder.getShopId());
        sepAcc.setSubAcctNo(subAcctNo);
        sepAcc.setTranNetMemberCode(dto.getTranNetMemberCode());
        sepAcc.setRegOrderNo(orderNo);
        sepAcc.setSuspendAmt(suspendAmt);
        sepAcc.setTranFee(tranFee);
        sepAcc.setRegStatus(1);
        sepAcc.setStatus(0);
        sepAcc.setAddTime(DateUtil.now());
        sepAcc.setUpdTime(DateUtil.now());

        sxoSafetyRegCreditService.save(sepAcc);

        try {
            IBaseClient baseClient = new RegisterBillSupportWithdrawApi(sxoSafetyLogService, taskExecutePoolConfig);
            HttpResult httpResult = baseClient.execute(json);
            JSONObject extenddata = handleError(httpResult);
            String jzbAcceptSeqNo = extenddata.getString("FrontSeqNo");

            String date = DateUtil.now();
            SxoSafetyRegCredit mod = new SxoSafetyRegCredit();
            mod.setId(sepAcc.getId());
            mod.setRegStatus(1);
            mod.setRegTime(date);
            mod.setCnsmrSeqNo(extenddata.getString(PaPayUtil.CNSMR_SEQ_NO));
            mod.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            sxoSafetyRegCreditService.updateById(mod);

            RegisterBillSupportWithdrawVo vo = new RegisterBillSupportWithdrawVo();
            vo.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            return vo;
        } catch (Exception e) {
            SxoSafetyRegCredit mod = new SxoSafetyRegCredit();
            mod.setId(sepAcc.getId());
            mod.setUpdTime(DateUtil.now());
            mod.setRegStatus(-1);
            mod.setErrorMsg(e.getMessage());
            sxoSafetyRegCreditService.updateById(mod);
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
        }
    }

    @Override
    public RegisterBillSupportWithdrawVo revRegisterBillSupportWithdraw(RegisterBillSupportWithdrawDto dto) {
        if (StrUtil.isEmpty(dto.getId())) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "id必须填写");
        }
        LambdaQueryWrapper<SxoSafetyRegCredit> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SxoSafetyRegCredit::getId, dto.getId());
        queryWrapper.eq(SxoSafetyRegCredit::getStatus, "0");
        queryWrapper.eq(SxoSafetyRegCredit::getRegStatus, "1");
        List<SxoSafetyRegCredit> credits = sxoSafetyRegCreditService.list(queryWrapper);
        if (credits.isEmpty()) {
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), "id错误或者已撤退挂账");
        }

        SxoSafetyRegCredit credit = credits.get(0);


        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6140");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        //订单信息
        json.put("SubAcctNo", credit.getSubAcctNo());
        json.put("TranNetMemberCode", credit.getTranNetMemberCode());
        json.put("OldOrderNo", credit.getRegOrderNo());
        json.put("CancelAmt", credit.getSuspendAmt());
        json.put("TranFee", credit.getTranFee());

        try {
            IBaseClient baseClient = new RevRegisterBillSupportWithdrawApi(sxoSafetyLogService, taskExecutePoolConfig);
            HttpResult httpResult = baseClient.execute(json);
            JSONObject extenddata = handleError(httpResult);
            String jzbAcceptSeqNo = extenddata.getString("FrontSeqNo");

            String date = DateUtil.now();
            SxoSafetyRegCredit mod = new SxoSafetyRegCredit();
            mod.setId(credit.getId());
            mod.setRegStatus(2);
            mod.setRegTime(date);
            mod.setRevCnsmrSeqNo(extenddata.getString(PaPayUtil.CNSMR_SEQ_NO));
            mod.setJzbAcceptRevNo(jzbAcceptSeqNo);
            sxoSafetyRegCreditService.updateById(mod);

            RegisterBillSupportWithdrawVo vo = new RegisterBillSupportWithdrawVo();
            vo.setJzbAcceptSeqNo(jzbAcceptSeqNo);
            return vo;
        } catch (Exception e) {
            SxoSafetyRegCredit mod = new SxoSafetyRegCredit();
            mod.setId(credit.getId());
            mod.setUpdTime(DateUtil.now());
            mod.setRegStatus(-2);
            mod.setErrorMsg("撤销失败：" + e.getMessage());
            sxoSafetyRegCreditService.updateById(mod);
            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
        }
    }

    @Override
    public TraFinalStatusQueryVo traFinalStatusQuery(TraFinalStatusQueryDto dto) {

//        TraFinalStatusQueryVo a = new TraFinalStatusQueryVo();
//
//        ThirdFreezeRechargeCancelDto tcd = new ThirdFreezeRechargeCancelDto();
//        tcd.setSaleId(dto.getId());
//        paOrderService.orderRefundToPhp(tcd);

        JSONObject json = new JSONObject();
        json.put("TxnCode", "KFEJZB6273");
        json.put("FundSummaryAcctNo", payConfig.getFundSummaryAcctNo());
        //订单信息
        json.put("OldJzbAcceptSeqNo", dto.getOldJzbAcceptSeqNo());

        try {
            IBaseClient baseClient = new TraFinalStatusQueryApi(sxoSafetyLogService, taskExecutePoolConfig);
            log.info("6273调平安入参："+json);
            log.info("6273调平安入参时间:{}", DateUtil.now());

            HttpResult httpResult = baseClient.execute(json);
            JSONObject extenddata = handleError(httpResult);
            log.info("6273调平安回参："+extenddata);
            log.info("6273调平安回参时间:{}", DateUtil.now());

            JSONObject obj = buildResult(extenddata);
            return JSONObject.parseObject(obj.toJSONString(), TraFinalStatusQueryVo.class);
        } catch (Exception e) {

            throw new BusinessException(CodeEnum.SERVER_ERROR.getCode(), e.getMessage());
        }

//      return a;
    }

}
